require('dotenv').config();
const { Client } = require("basic-ftp") 
const { Readable } = require('stream') // 新增stream模块


// 上传文件到FTP服务器
async function uploadFileToFtp( readFile, fileName) {
    const client = new Client()
    client.ftp.verbose = true
    try {
        await client.access({
            host: process.env.FTP_HOST,
            user: process.env.FTP_USER,
            password: process.env.FTP_PASSWORD,
            secure: false
        })
        const readableStream = Readable.from(readFile) // 将Buffer转换为可读流
        console.log('已连接：',await client.list())
        await client.uploadFrom(readableStream, fileName)
    }
    catch(err) {
        console.log('错误：', err)
    }
    client.close()
}

// 删除FTP服务器上的文件
async function deleteFileFromFtp(remotePath) {
    const client = new Client()
    client.ftp.verbose = true
    try {
        await client.access({
            host: process.env.FTP_HOST,
            user: process.env.FTP_USER,
            password: process.env.FTP_PASSWORD,
            secure: false
        })
        await client.remove(remotePath)
        return true
    } catch(err) {
        console.log('FTP删除错误:', err)
        return false
    } finally {
        client.close()
    }
}

module.exports = { uploadFileToFtp, deleteFileFromFtp }; // 修改导出